"""
系统服务模块
提供系统管理相关功能，包括字体管理
"""

import os
import subprocess
import logging
from typing import Dict, List, Optional

class SystemService:
    """系统服务类"""
    
    def __init__(self):
        """初始化系统服务"""
        self._font_info = self._init_font_info()
    
    def _init_font_info(self) -> Dict[str, Dict[str, str]]:
        """
        初始化字体信息字典
        
        Returns:
            Dict: 字体信息字典
        """
        return {
            'pingfang': {
                'name': 'PingFang SC',
                'description': '苹方字体，macOS系统中文字体',
                'path': '/System/Library/Fonts/PingFang.ttc',
                'type': 'ttc',
                'supported_languages': ['zh', 'ja', 'ko']
            },
            'heiti': {
                'name': 'Heiti SC',
                'description': '黑体字体，macOS系统中文字体',
                'path': '/System/Library/Fonts/STHeiti Medium.ttc',
                'type': 'ttc',
                'supported_languages': ['zh', 'ja', 'ko']
            },
            'dejavu': {
                'name': 'DejaVu Sans',
                'description': 'DejaVu字体，支持多种语言（中文支持有限）',
                'path': '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
                'type': 'ttf',
                'supported_languages': ['en', 'zh', 'ja', 'ko', 'ar', 'he', 'th']
            },
            'liberation': {
                'name': 'Liberation Sans',
                'description': 'Liberation字体，开源替代字体（中文支持有限）',
                'path': '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf',
                'type': 'ttf',
                'supported_languages': ['en', 'zh', 'ja', 'ko']
            },
            'ubuntu': {
                'name': 'Ubuntu',
                'description': 'Ubuntu字体，Ubuntu系统默认字体（中文支持有限）',
                'path': '/usr/share/fonts/truetype/ubuntu/Ubuntu-Regular.ttf',
                'type': 'ttf',
                'supported_languages': ['en', 'zh', 'ja', 'ko']
            }
        }
    
    def get_available_fonts(self) -> List[Dict[str, str]]:
        """
        获取系统可用的字体列表
        
        Returns:
            List[Dict]: 可用字体列表
        """
        available_fonts = []
        
        for font_key, font_info in self._font_info.items():
            if self._check_font_available(font_info['path']):
                available_fonts.append({
                    'key': font_key,
                    'name': font_info['name'],
                    'description': font_info['description'],
                    'path': font_info['path'],
                    'type': font_info['type'],
                    'supported_languages': font_info['supported_languages']
                })
        
        return available_fonts
    
    def get_font_path(self, font_key: str) -> Optional[str]:
        """
        获取指定字体的路径
        
        Args:
            font_key (str): 字体键名
            
        Returns:
            Optional[str]: 字体文件路径，如果不存在返回None
        """
        if font_key not in self._font_info:
            return None
        
        font_info = self._font_info[font_key]
        if self._check_font_available(font_info['path']):
            return font_info['path']
        
        return None
    
    def get_font_info(self, font_key: str) -> Optional[Dict[str, str]]:
        """
        获取指定字体的详细信息
        
        Args:
            font_key (str): 字体键名
            
        Returns:
            Optional[Dict]: 字体信息，如果不存在返回None
        """
        if font_key not in self._font_info:
            return None
        
        font_info = self._font_info[font_key].copy()
        font_info['available'] = self._check_font_available(font_info['path'])
        
        return font_info
    
    def get_recommended_font(self, language: str = 'zh') -> Optional[str]:
        """
        根据语言获取推荐字体路径
        
        Args:
            language (str): 语言代码，默认为中文
            
        Returns:
            Optional[str]: 推荐字体路径
        """
        # 按优先级排序的字体键
        font_priorities = {
            'zh': ['pingfang', 'heiti', 'dejavu', 'liberation', 'ubuntu'],
            'ja': ['pingfang', 'heiti', 'dejavu', 'liberation', 'ubuntu'],
            'ko': ['pingfang', 'heiti', 'dejavu', 'liberation', 'ubuntu'],
            'en': ['dejavu', 'liberation', 'ubuntu'],
            'ar': ['dejavu'],
            'he': ['dejavu'],
            'th': ['dejavu'],
            'hi': ['dejavu'],
            'bn': ['dejavu']
        }
        
        # 获取对应语言的字体优先级
        priorities = font_priorities.get(language, font_priorities['en'])
        
        # 按优先级查找可用字体
        for font_key in priorities:
            font_path = self.get_font_path(font_key)
            if font_path:
                return font_path
        
        # 如果没有找到特定语言的字体，返回第一个可用字体
        available_fonts = self.get_available_fonts()
        if available_fonts:
            return available_fonts[0]['path']
        
        return None
    
    def _check_font_available(self, font_path: str) -> bool:
        """
        检查字体文件是否可用
        
        Args:
            font_path (str): 字体文件路径
            
        Returns:
            bool: 字体是否可用
        """
        try:
            return os.path.exists(font_path) and os.path.isfile(font_path)
        except Exception as e:
            logging.warning(f"检查字体文件失败 {font_path}: {e}")
            return False
    
    def test_font_rendering(self, font_path: str) -> bool:
        """
        测试字体渲染功能
        
        Args:
            font_path (str): 字体文件路径
            
        Returns:
            bool: 字体渲染是否正常
        """
        try:
            # 使用FFmpeg测试字体渲染
            test_cmd = [
                'ffmpeg', '-y',
                '-f', 'lavfi',
                '-i', 'testsrc=duration=1:size=320x240:rate=1',
                '-vf', f'drawtext=text=\'Test Font\':fontfile={font_path}:fontsize=24:fontcolor=white:x=10:y=10',
                '-frames:v', '1',
                '/tmp/font_test.png'
            ]
            
            result = subprocess.run(test_cmd, capture_output=True, text=True, timeout=30)
            return result.returncode == 0
            
        except Exception as e:
            logging.error(f"字体渲染测试失败 {font_path}: {e}")
            return False
    
    def get_system_font_info(self) -> Dict[str, any]:
        """
        获取系统字体信息
        
        Returns:
            Dict: 系统字体信息
        """
        available_fonts = self.get_available_fonts()
        
        # 测试字体渲染
        rendering_tests = {}
        for font in available_fonts:
            rendering_tests[font['key']] = self.test_font_rendering(font['path'])
        
        return {
            'total_fonts': len(self._font_info),
            'available_fonts': len(available_fonts),
            'fonts': available_fonts,
            'rendering_tests': rendering_tests,
            'recommended_fonts': {
                'zh': self.get_recommended_font('zh'),
                'en': self.get_recommended_font('en'),
                'ja': self.get_recommended_font('ja'),
                'ko': self.get_recommended_font('ko')
            }
        }

# 创建全局实例
system_service = SystemService() 